﻿using NewChillers.Helpers;
using NewChillers.Models;
using NewChillers.Models.Events;
using NewChillers.Utils;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace NewChillers.ViewModels
{
    public class IOViewModel : ObservableObject
    {
        #region 枚举
        // 枚举：阀门状态
        public enum ValveStatus
        {
            Opened, // 已打开
            Closed  // 已关闭
        }
        #endregion

        #region 属性
        private UserModel _currentUser;
        private readonly ShellViewModel _shellViewModel;

        #region 属性 - 真空泵 - VP
        // 单一状态源：直接反映设备状态
        private ValveStatus _currentStatusVP = ValveStatus.Closed;
        private string _statusMessageVP = "系统就绪"; // 初始Msg

        public ValveStatus CurrentStatusVP
        {
            get => _currentStatusVP;
            private set
            {
                if (_currentStatusVP != value)
                {
                    _currentStatusVP = value;
                    RaisePropertyChanged();
                    // 自动更新所有相关属性
                    RaisePropertyChanged(nameof(IsOpenedVP));
                    CommandManager.InvalidateRequerySuggested(); // 刷新全局UI 可用性 开销较大 暂用
                }
            }
        }

        // 计算属性，避免状态冗余
        public bool IsOpenedVP => CurrentStatusVP == ValveStatus.Opened;

        public string StatusMessageVP
        {
            get => _statusMessageVP;
            set => SetProperty(ref _statusMessageVP, value);
        }
        #endregion

        #region 属性 - 真空泵 阀门 - VPV
        private ValveStatus _currentStatusVPV = ValveStatus.Closed;
        private string _statusMessageVPV = "系统就绪";

        public ValveStatus CurrentStatusVPV
        {
            get => _currentStatusVPV;
            private set
            {
                if (_currentStatusVPV != value)
                {
                    _currentStatusVPV = value;
                    RaisePropertyChanged();
                    RaisePropertyChanged(nameof(IsOpenedVPV));
                    CommandManager.InvalidateRequerySuggested();
                }
            }
        }

        public bool IsOpenedVPV => CurrentStatusVPV == ValveStatus.Opened;

        public string StatusMessageVPV
        {
            get => _statusMessageVPV;
            set => SetProperty(ref _statusMessageVPV, value);
        }
        #endregion

        #region 属性 - 充氦气 阀门 - HCV
        private ValveStatus _currentStatusHCV = ValveStatus.Closed;
        private string _statusMessageHCV = "系统就绪";

        public ValveStatus CurrentStatusHCV
        {
            get => _currentStatusHCV;
            private set
            {
                if (_currentStatusHCV != value)
                {
                    _currentStatusHCV = value;
                    RaisePropertyChanged();
                    RaisePropertyChanged(nameof(IsOpenedHCV));
                    CommandManager.InvalidateRequerySuggested();
                }
            }
        }

        public bool IsOpenedHCV => CurrentStatusHCV == ValveStatus.Opened;

        public string StatusMessageHCV
        {
            get => _statusMessageHCV;
            set => SetProperty(ref _statusMessageHCV, value);
        }
        #endregion

        #region 属性 - 进气 总阀门 - IGV
        private ValveStatus _currentStatusIGV = ValveStatus.Closed;
        private string _statusMessageIGV = "系统就绪";

        public ValveStatus CurrentStatusIGV
        {
            get => _currentStatusIGV;
            private set
            {
                if (_currentStatusIGV != value)
                {
                    _currentStatusIGV = value;
                    RaisePropertyChanged();
                    RaisePropertyChanged(nameof(IsOpenedIGV));
                    CommandManager.InvalidateRequerySuggested();
                }
            }
        }

        public bool IsOpenedIGV => CurrentStatusIGV == ValveStatus.Opened;

        public string StatusMessageIGV
        {
            get => _statusMessageIGV;
            set => SetProperty(ref _statusMessageIGV, value);
        }
        #endregion

        #region 属性 - 排气 总阀门 - OGV
        private ValveStatus _currentStatusOGV = ValveStatus.Closed;
        private string _statusMessageOGV = "系统就绪";

        public ValveStatus CurrentStatusOGV
        {
            get => _currentStatusOGV;
            private set
            {
                if (_currentStatusOGV != value)
                {
                    _currentStatusOGV = value;
                    RaisePropertyChanged();
                    RaisePropertyChanged(nameof(IsOpenedOGV));
                    CommandManager.InvalidateRequerySuggested();
                }
            }
        }

        public bool IsOpenedOGV => CurrentStatusOGV == ValveStatus.Opened;

        public string StatusMessageOGV
        {
            get => _statusMessageOGV;
            set => SetProperty(ref _statusMessageOGV, value);
        }
        #endregion
        #endregion

        #region 命令
        public ICommand OpenCommandVP { get; } // 打开 真空泵
        public ICommand CloseCommandVP { get; } // 关闭 真空泵
        public ICommand OpenCommandVPV { get; } // 打开 真空泵 阀门
        public ICommand CloseCommandVPV { get; } // 关闭 真空泵 阀门
        public ICommand OpenCommandHCV { get; } // 打开 充氦气 阀门
        public ICommand CloseCommandHCV { get; } // 关闭 充氦气 阀门
        public ICommand OpenCommandIGV { get; } // 打开 进气 总阀门
        public ICommand CloseCommandIGV { get; } // 关闭 进气 总阀门
        public ICommand OpenCommandOGV { get; } // 打开 排气 总阀门
        public ICommand CloseCommandOGV { get; } // 关闭 排气 总阀门
        #endregion

        #region 构造函数
        public IOViewModel(UserModel userModel, ShellViewModel shellViewModel)
        {
            _currentUser = userModel;
            _shellViewModel = shellViewModel;

            // 初始化


            // IO操作
            // 1 - 真空泵 - VP
            OpenCommandVP = new RelayCommand(
                execute: (param) => OpenVP(),
                canExecute: (param) => CurrentStatusVP == ValveStatus.Closed
            );
            CloseCommandVP = new RelayCommand(
                execute: (param) => CloseVP(),
                canExecute: (param) => CurrentStatusVP == ValveStatus.Opened
            );

            // 2 - 真空泵 阀门 - VPV
            OpenCommandVPV = new RelayCommand(
                execute: (param) => OpenVPV(),
                canExecute: (param) => CurrentStatusVPV == ValveStatus.Closed
            );
            CloseCommandVPV = new RelayCommand(
                execute: (param) => CloseVPV(),
                canExecute: (param) => CurrentStatusVPV == ValveStatus.Opened
            );

            // 3 - 充氦气 阀门 - HCV
            OpenCommandHCV = new RelayCommand(
                execute: (param) => OpenHCV(),
                canExecute: (param) => CurrentStatusHCV == ValveStatus.Closed
            );
            CloseCommandHCV = new RelayCommand(
                execute: (param) => CloseHCV(),
                canExecute: (param) => CurrentStatusHCV == ValveStatus.Opened
            );

            // 4 - 进气 总阀门 - IGV
            OpenCommandIGV = new RelayCommand(
                execute: (param) => OpenIGV(),
                canExecute: (param) => CurrentStatusIGV == ValveStatus.Closed
            );
            CloseCommandIGV = new RelayCommand(
                execute: (param) => CloseIGV(),
                canExecute: (param) => CurrentStatusIGV == ValveStatus.Opened
            );

            // 5 - 排气 总阀门 - OGV
            OpenCommandOGV = new RelayCommand(
                execute: (param) => OpenOGV(),
                canExecute: (param) => CurrentStatusOGV == ValveStatus.Closed
            );
            CloseCommandOGV = new RelayCommand(
                execute: (param) => CloseOGV(),
                canExecute: (param) => CurrentStatusOGV == ValveStatus.Opened
            );

            // 订阅
            _shellViewModel.UserInfoUpdate += OnUserInfoUpdate;
        }
        #endregion

        #region IO操作
        #region IO操作 - 1 - 真空泵 - VP
        private void OpenVP()
        {
            try
            {
                // 执行实际的打开逻辑（同步方式）
                ExecuteOpenVP();

                // 启动成功
                CurrentStatusVP = ValveStatus.Opened;
                StatusMessageVP = "已打开 - " + DateTime.Now.ToString("HH:mm:ss");
                LogHelper.Info(this.GetType(), "[IO操作] | 真空泵 打开", _currentUser.UserAccount);
            }
            catch (Exception ex)
            {
                // 启动失败
                CurrentStatusVP = ValveStatus.Closed;
                StatusMessageVP = $"打开失败: {ex.Message}";
                LogHelper.Error(this.GetType(), "[IO操作] | 真空泵 打开失败", _currentUser.UserAccount);
            }
        }

        private void CloseVP()
        {
            try
            {
                // 执行实际的关闭逻辑（同步方式）
                ExecuteCloseVP();

                // 停止成功
                CurrentStatusVP = ValveStatus.Closed;
                StatusMessageVP = "已关闭 - " + DateTime.Now.ToString("HH:mm:ss");
                LogHelper.Info(this.GetType(), "[IO操作] | 真空泵 关闭", _currentUser.UserAccount);
            }
            catch (Exception ex)
            {
                // 停止失败，回退到运行状态
                CurrentStatusVP = ValveStatus.Opened;
                StatusMessageVP = $"关闭失败: {ex.Message}";
                LogHelper.Error(this.GetType(), "[IO操作] | 真空泵 关闭失败", _currentUser.UserAccount);
            }
        }

        /// <summary>
        /// 实际的打开逻辑
        /// </summary>
        private void ExecuteOpenVP()
        {
            // _plcService.WriteStartCommand();
            // if (!_plcService.VerifyRunningStatus())
            //     throw new InvalidOperationException("未正确打开");
        }

        /// <summary>
        /// 实际的关闭逻辑
        /// </summary>
        private void ExecuteCloseVP()
        {
            // _plcService.WriteStopCommand();
            // if (!_plcService.VerifyStoppedStatus())
            //     throw new InvalidOperationException("未正确关闭");
        }
        #endregion

        #region IO操作 - 2 - 真空泵 阀门 - VPV
        private void OpenVPV()
        {
            try
            {
                ExecuteOpenVPV();

                CurrentStatusVPV = ValveStatus.Opened;
                StatusMessageVPV = "已打开 - " + DateTime.Now.ToString("HH:mm:ss");
                LogHelper.Info(this.GetType(), "[IO操作] | 真空泵阀门 打开", _currentUser.UserAccount);
            }
            catch (Exception ex)
            {
                CurrentStatusVPV = ValveStatus.Closed;
                StatusMessageVPV = $"打开失败: {ex.Message}";
                LogHelper.Error(this.GetType(), "[IO操作] | 真空泵阀门 打开失败", _currentUser.UserAccount);
            }
        }

        private void CloseVPV()
        {
            try
            {
                ExecuteCloseVPV();

                CurrentStatusVPV = ValveStatus.Closed;
                StatusMessageVPV = "已关闭 - " + DateTime.Now.ToString("HH:mm:ss");
                LogHelper.Info(this.GetType(), "[IO操作] | 真空泵阀门 关闭", _currentUser.UserAccount);
            }
            catch (Exception ex)
            {
                CurrentStatusVPV = ValveStatus.Opened;
                StatusMessageVPV = $"关闭失败: {ex.Message}";
                LogHelper.Error(this.GetType(), "[IO操作] | 真空泵阀门 关闭失败", _currentUser.UserAccount);
            }
        }

        /// <summary>
        /// 实际的打开逻辑
        /// </summary>
        private void ExecuteOpenVPV()
        {
            // _plcService.WriteStartCommand();
            // if (!_plcService.VerifyRunningStatus())
            //     throw new InvalidOperationException("未正确打开");
        }

        /// <summary>
        /// 实际的关闭逻辑
        /// </summary>
        private void ExecuteCloseVPV()
        {
            // _plcService.WriteStopCommand();
            // if (!_plcService.VerifyStoppedStatus())
            //     throw new InvalidOperationException("未正确关闭");
        }
        #endregion

        #region IO操作 - 3 - 充氦气 - HCV
        private void OpenHCV()
        {
            try
            {
                ExecuteOpenHCV();

                CurrentStatusHCV = ValveStatus.Opened;
                StatusMessageHCV = "已打开 - " + DateTime.Now.ToString("HH:mm:ss");
                LogHelper.Info(this.GetType(), "[IO操作] | 充氦气阀门 打开", _currentUser.UserAccount);
            }
            catch (Exception ex)
            {
                CurrentStatusHCV = ValveStatus.Closed;
                StatusMessageHCV = $"打开失败: {ex.Message}";
                LogHelper.Error(this.GetType(), "[IO操作] | 充氦气阀门 打开失败", _currentUser.UserAccount);
            }
        }

        private void CloseHCV()
        {
            try
            {
                ExecuteCloseHCV();

                CurrentStatusHCV = ValveStatus.Closed;
                StatusMessageHCV = "已关闭 - " + DateTime.Now.ToString("HH:mm:ss");
                LogHelper.Info(this.GetType(), "[IO操作] | 充氦气阀门 关闭", _currentUser.UserAccount);
            }
            catch (Exception ex)
            {
                CurrentStatusHCV = ValveStatus.Opened;
                StatusMessageHCV = $"关闭失败: {ex.Message}";
                LogHelper.Error(this.GetType(), "[IO操作] | 充氦气阀门 关闭失败", _currentUser.UserAccount);
            }
        }

        /// <summary>
        /// 实际的打开逻辑
        /// </summary>
        private void ExecuteOpenHCV()
        {
            // _plcService.WriteStartCommand();
            // if (!_plcService.VerifyRunningStatus())
            //     throw new InvalidOperationException("未正确打开");
        }

        /// <summary>
        /// 实际的关闭逻辑
        /// </summary>
        private void ExecuteCloseHCV()
        {
            // _plcService.WriteStopCommand();
            // if (!_plcService.VerifyStoppedStatus())
            //     throw new InvalidOperationException("未正确关闭");
        }
        #endregion

        #region IO操作 - 4 - 进气 总阀门 - IGV
        private void OpenIGV()
        {
            try
            {
                ExecuteOpenIGV();

                CurrentStatusIGV = ValveStatus.Opened;
                StatusMessageIGV = "已打开 - " + DateTime.Now.ToString("HH:mm:ss");
                LogHelper.Info(this.GetType(), "[IO操作] | 进气总阀 打开", _currentUser.UserAccount);
            }
            catch (Exception ex)
            {
                CurrentStatusIGV = ValveStatus.Closed;
                StatusMessageIGV = $"打开失败: {ex.Message}";
                LogHelper.Error(this.GetType(), "[IO操作] | 进气总阀 打开失败", _currentUser.UserAccount);
            }
        }

        private void CloseIGV()
        {
            try
            {
                ExecuteCloseIGV();

                CurrentStatusIGV = ValveStatus.Closed;
                StatusMessageIGV = "已关闭 - " + DateTime.Now.ToString("HH:mm:ss");
                LogHelper.Info(this.GetType(), "[IO操作] | 进气总阀 关闭", _currentUser.UserAccount);
            }
            catch (Exception ex)
            {
                CurrentStatusIGV = ValveStatus.Opened;
                StatusMessageIGV = $"关闭失败: {ex.Message}";
                LogHelper.Error(this.GetType(), "[IO操作] | 进气总阀 关闭失败", _currentUser.UserAccount);
            }
        }

        /// <summary>
        /// 实际的打开逻辑
        /// </summary>
        private void ExecuteOpenIGV()
        {
            // _plcService.WriteStartCommand();
            // if (!_plcService.VerifyRunningStatus())
            //     throw new InvalidOperationException("未正确打开");
        }

        /// <summary>
        /// 实际的关闭逻辑
        /// </summary>
        private void ExecuteCloseIGV()
        {
            // _plcService.WriteStopCommand();
            // if (!_plcService.VerifyStoppedStatus())
            //     throw new InvalidOperationException("未正确关闭");
        }
        #endregion

        #region IO操作 - 5 - 排气 总阀门 - OGV
        private void OpenOGV()
        {
            try
            {
                ExecuteOpenOGV();

                CurrentStatusOGV = ValveStatus.Opened;
                StatusMessageOGV = "已打开 - " + DateTime.Now.ToString("HH:mm:ss");
                LogHelper.Info(this.GetType(), "[IO操作] | 排气总阀 打开", _currentUser.UserAccount);
            }
            catch (Exception ex)
            {
                CurrentStatusOGV = ValveStatus.Closed;
                StatusMessageOGV = $"打开失败: {ex.Message}";
                LogHelper.Error(this.GetType(), "[IO操作] | 排气总阀 打开失败", _currentUser.UserAccount);
            }
        }

        private void CloseOGV()
        {
            try
            {
                ExecuteCloseOGV();

                CurrentStatusOGV = ValveStatus.Closed;
                StatusMessageOGV = "已关闭 - " + DateTime.Now.ToString("HH:mm:ss");
                LogHelper.Info(this.GetType(), "[IO操作] | 排气总阀 关闭", _currentUser.UserAccount);
            }
            catch (Exception ex)
            {
                CurrentStatusOGV = ValveStatus.Opened;
                StatusMessageOGV = $"关闭失败: {ex.Message}";
                LogHelper.Error(this.GetType(), "[IO操作] | 排气总阀 关闭失败", _currentUser.UserAccount);
            }
        }

        /// <summary>
        /// 实际的打开逻辑
        /// </summary>
        private void ExecuteOpenOGV()
        {
            // _plcService.WriteStartCommand();
            // if (!_plcService.VerifyRunningStatus())
            //     throw new InvalidOperationException("未正确打开");
        }

        /// <summary>
        /// 实际的关闭逻辑
        /// </summary>
        private void ExecuteCloseOGV()
        {
            // _plcService.WriteStopCommand();
            // if (!_plcService.VerifyStoppedStatus())
            //     throw new InvalidOperationException("未正确关闭");
        }
        #endregion
        #endregion

        #region 更新当前登录用户的信息 事件处理
        /// <summary>
        /// 接收到通知
        /// </summary>
        private void OnUserInfoUpdate(object sender, UserInfoUpdateEventArgs e)
        {
            // 空值检查，避免NullReferenceException
            if (e?.UpdatedUser != null)
            {
                _currentUser = e.UpdatedUser;
                Debug.WriteLine("IO页面|用户信息已更新");
            }
            else
            {
                Debug.WriteLine("收到空的事件参数");
            }
        }

        /// <summary>
        /// 析构函数中的事件取消订阅
        /// </summary>
        ~IOViewModel()
        {
            _shellViewModel.UserInfoUpdate -= OnUserInfoUpdate;
        }
        #endregion
    }
}
